---
title: Executing Queries
description: Executing queries
keywords:
  - electrodb
  - docs
  - concepts
  - dynamodb
  - FilterExpression
  - ConditionExpression
  - get
  - go
  - params
layout: ../../../layouts/MainLayout.astro
---

import ExampleSetup from "../../../partials/entity-query-example-setup.mdx";

<ExampleSetup />

In DynamoDB, an index serves as a data structure designed to improve the efficiency of data queries within a table. DynamoDB offers two types of indexes: local secondary indexes and global secondary indexes.

A local secondary index enables queries based on the table's primary key while offering the flexibility to use a different sort key. This feature is useful for querying data in ways that differ from the default sort key associated with the table's primary key.

On the other hand, a global secondary index allows for queries based on a completely different primary key than the one associated with the table. This is particularly useful for querying data unrelated to the table's primary key, or for alternative query methods.

Overall, utilizing indexes in DynamoDB can significantly improve query performance, especially in large tables with extensive data. Efficient querying is crucial for optimal application performance.

In ElectroDB, queries are constructed around the 'Access Patterns' defined in the Schema. They can leverage partial key 'Composite Attributes' to enable efficient lookups. ElectroDB defines partition and sort keys as composites of one or more attributes, which is elaborated in the [Modeling Indexes](/en/modeling/indexes) section.

## Query Methods

Retrieving data from DynamoDB is accomplished by using one of the four query methods: `query`, `scan`, `get`, and `batchGet`. The `query` method is used to retrieve data from a table or index by performing a key lookup. The `scan` method is used to retrieve data from a table by scanning the entire table. The `get` method is used to retrieve a single item from a table by performing a key lookup. The `batchGet` method is used to retrieve multiple items from a table by performing multiple key lookups.

Additionally, ElectroDB offers a few additional methods built on top of DynamoDB's offerings: `find` and `match`. These methods will perform a `query` or `scan` depending on the provided arguments. Below is a table that explains each ElectroDB method, which DynamoDB operation the method maps to, and a short description of the method's purpose.

| ElectroDB Method                  | DynamoDB Method   | Purpose                                                                                                                                                                                                                                            |
| --------------------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [get](/en/queries/get)            | `get`             | Returns a single item, specified by its primary key.                                                                                                                                                                                               |
| [batchGet](/en/queries/batch-get) | `batchGet`        | Returns a set of attributes for multiple items from one or more tables.                                                                                                                                                                            |
| [query](/en/queries/query)        | `query`           | Queries a table or index for items that match the specified primary key value.                                                                                                                                                                     |
| [scan](/en/queries/scan)          | `scan`            | Scans the table and returns all matching items.                                                                                                                                                                                                    |
| [match](/en/queries/match)        | `query` or `scan` | The `match` method will attempt to build the most performant index keys with the attributes provided. ElectroDB identifies which index it can be "most" fulfilled with the index provided, and will fallback to a `scan` if no index can be built. |
| [find](/en/queries/find)          | `query` or `scan` | the `find` method performs the same index seeking behavior but will also apply all provided values as filters instead of only using provided attributes to build index keys.                                                                       |

## Mutation Methods

DynamoDB offers three methods for updating and creating records: `put`, `update`, and `batchWrite`. For the uninitiated, all three of these methods will create an item if it doesn't exist. The difference between `put`/`batchWrite` and `update` this that a `put` will overwrite the existing item while an `update` will only modify the fields provided if the item already exists.

Additionally, ElectroDB offers a few mutation methods beyond `put`, `update`, and `delete` to more ergonomically fit your use case. Below is a table that explains each ElectroDB method, which DynamoDB operation the method maps to, and a short description of the method's purpose.

| ElectroDB Method                    | DynamoDB Method        | Purpose                                                                                                                                                                               |
| ----------------------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [put](/en/mutations/put)            | `put`, `batchWrite`    | Creates or overwrites an existing item with the values provided                                                                                                                       |
| [batchPut](/en/mutations/batch-put) | `batchWrite`           | Creates or overwrites multiple items with the values provided                                                                                                                         |
| [create](/en/mutations/create)      | `put`                  | Creates an item if the item does not currently exist, or throws if the item exists                                                                                                    |
| [upsert](/en/mutations/upsert)      | `update`               | Upsert is similar to `put` in that it will create a record if one does not exist, except `upsert` perform an update if that record already exists.                                    |
| [update](/en/mutations/update)      | `update`               | Performs update on an existing record or creates a new record per the DynamoDB spec ([read more](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.html)) |
| [patch](/en/mutations/patch)        | `update`               | Performs an update on existing item or throws if that item does not already exist.                                                                                                    |
| [delete](/en/mutations/delete)      | `delete`, `batchWrite` | Deletes an item regardless of whether or not the specified item exists                                                                                                                |
| [remove](/en/mutations/remove)      | `delete`               | Deletes an item or throws if the item does not currently exist                                                                                                                        |

## Execution Methods

All query chains end with either a `.go()`, `.params()` method invocation. These terminal methods will either execute the query to DynamoDB (`.go()`) or return formatted parameters for use with the DynamoDB docClient (`.params()`).

Both `.params()` and `.go()` take a query configuration object which is detailed more in the section [Execution Options](/en/core-concepts/executing-queries).

### Params

The `params` method _ends_ a query chain, and synchronously formats your query into an object ready for the DynamoDB docClient.

> For more information on the options available in the `config` object, checkout the section [Execution Options](/en/core-concepts/executing-queries)

#### Example

```typescript
const params = MallStores.query
  .leases({ mallId })
  .between({ leaseEndDate: "2020-06-01" }, { leaseEndDate: "2020-07-31" })
  .where(({ rent }, { lte }) => lte(rent, "5000.00"))
  .params();
```

#### Output

```json
{
  "IndexName": "idx2",
  "TableName": "electro",
  "ExpressionAttributeNames": {
    "#rent": "rent",
    "#pk": "idx2pk",
    "#sk1": "idx2sk"
  },
  "ExpressionAttributeValues": {
    ":rent1": "5000.00",
    ":pk": "$mallstoredirectory_1#mallid_eastpointe",
    ":sk1": "$mallstore#leaseenddate_2020-06-01#rent_",
    ":sk2": "$mallstore#leaseenddate_2020-07-31#rent_"
  },
  "KeyConditionExpression": "#pk = :pk and #sk1 BETWEEN :sk1 AND :sk2",
  "FilterExpression": "#rent <= :rent1"
}
```

### Go

The `go` method _ends_ a query chain, and asynchronously queries DynamoDB with the `client` provided in the model.

> For more information on the options available in the `config` object, check out the section [Execution Options](/en/core-concepts/executing-queries)

#### Example

```typescript
const results = await MallStores.query
  .leases({ mallId })
  .between({ leaseEndDate: "2020-06-01" }, { leaseEndDate: "2020-07-31" })
  .where(({ rent }, { lte }) => lte(rent, "5000.00"))
  .go();
```

#### Output

```typescript
{
  data: Array<YOUR_SCHEMA>,
  cursor: string | undefined
}
```

### Execution Options

Execution options can be added the `.params()` and `.go()` to change query behavior or add customer parameters to a query.

By default, **ElectroDB** enables you to work with records as the names and properties defined in the model. Additionally, it removes the need to deal directly with the docClient parameters which can be complex for a team without as much experience with DynamoDB. The Query Options object can be passed to both the `.params()` and `.go()` methods when building you query. Below are the options available:

import PartialExample from "../../../partials/query-options.mdx";

<PartialExample />